package com.treasure.hunt.main

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.*
import com.fm.openinstall.OpenInstall
import com.fm.openinstall.listener.AppWakeUpAdapter
import com.fm.openinstall.model.AppData
import com.google.android.material.tabs.TabLayout
import com.kwai.monitor.log.TurboAgent
import com.module.lemlin.base.loadRoundImage
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.module.lemlin.util.AnimManager
import com.treasure.hunt.R
import com.treasure.hunt.app.AppConstance
import com.treasure.hunt.app.THApplication
import com.treasure.hunt.entity.Action
import com.treasure.hunt.entity.MainBean
import com.treasure.hunt.entity.SchemeData
import com.treasure.hunt.entity.TaskSign
import com.treasure.hunt.mine.MineCardActivity
import com.treasure.hunt.mode.MainViewMode
import com.treasure.hunt.popup.DialogCardPopup
import com.treasure.hunt.popup.DialogFlopPopup
import com.treasure.hunt.popup.DialogGuidePopup
import com.treasure.hunt.popup.DialogHintPopup
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.include_guide_4.view.*
import kotlinx.android.synthetic.main.popup_dialog_guide.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class MainActivity : ViewModeActivity<MainViewMode>() {

    private val fragmentLifecycleCallbacks = object : FragmentManager.FragmentLifecycleCallbacks() {
        override fun onFragmentResumed(fm: FragmentManager, fragment: Fragment) {
            super.onFragmentResumed(fm, fragment)
        }
    }

    private var mSchemeData: SchemeData? = null
    private val cardPopup: DialogCardPopup by lazy {
        DialogCardPopup(context = this, onConfirmReceive = {
            mSchemeData?.let {
                val cardId: String? = it.cart_id
                val receiveUserId: String? = it.receive_user_id
                if (cardId.isNullOrEmpty() || receiveUserId.isNullOrEmpty())
                    return@let
                viewModel.cardUserGiveCard(cardId, receiveUserId)
            }
        }, onConfirmGive = {
            mSchemeData?.let {
                val giveId: String? = it.give_id
                if (giveId.isNullOrEmpty())
                    return@let
                viewModel.cardReceiveCart(giveId)
            }
        })
    }


    private val hintPopup: DialogHintPopup by lazy {
        DialogHintPopup(context = this,
            onConfirm = { view, type ->
                hintPopup.dismiss()
                if (type != DialogHintPopup.Type.SHOW_UPDATE)
                    return@DialogHintPopup
                viewModel.otherAppLiveData.value?.httpData?.data?.let {
                    download(it.downloadurl)
                }
            },
            onCancel = { view, type ->
                hintPopup.dismiss()
            })
    }

    private val guidePopup: DialogGuidePopup by lazy {
        DialogGuidePopup(context = window.context) {
            if (it.id == R.id.llDialogGuideBottom1) {
                tab_view_main.getTabAt(1)?.select()
            } else if (it.id == R.id.llDialogGuideBottom2) {
                tab_view_main.getTabAt(2)?.select()
            } else if (it.id == R.id.flDialogGuideTask) {
                tab_view_main.getTabAt(3)?.select()
            } else if (it.id == R.id.flDialogGuideCard) {
                SPStaticUtils.put(AppConstance.KEY_NAME_GUIDE, true)
                guidePopup.dismiss()
                viewModel.otherGetVersion()
                viewModel.taskSignList(isMain = true)
            }
        }
    }


    private val flopPopup: DialogFlopPopup by lazy {
        DialogFlopPopup(context = this, onAnimationEnd = {

            if (it.tag as Boolean) {
                viewModel.taskSignList()
                return@DialogFlopPopup
            }

            if (it.drawable == null)
                return@DialogFlopPopup
            val mainBean: MainBean<Action, Any> = MainBean(
                type = Action.GO_MINE
            )
            EventBus.getDefault().post(mainBean)

            val circleImageView = ImageView(this)
            val layoutParams = LinearLayout.LayoutParams(
                ConvertUtils.dp2px(50f), ConvertUtils.dp2px(50f)
            )
            circleImageView.layoutParams = layoutParams
            circleImageView.loadRoundImage(it.drawable, radius = 25)

            val animManager: AnimManager = AnimManager.Builder()
                .with(this)
                .animModule(AnimManager.AnimModule.BIG_CIRCLE)
                .time(1200)
                .listener(object : AnimManager.AnimListener {
                    override fun setAnimBegin(a: AnimManager) {}
                    override fun setAnimEnd(a: AnimManager) {
                        a.stopAnim()
                    }
                })
                .animView(circleImageView)
                .build()
            animManager.startAnim(
                intArrayOf(
                    (ScreenUtils.getAppScreenWidth() / 2) - ConvertUtils.dp2px(25f),
                    ScreenUtils.getAppScreenHeight() / 2
                ), intArrayOf(
                    ScreenUtils.getAppScreenWidth() / 8 * 7,
                    ScreenUtils.getAppScreenHeight()
                )
            )
        }, onDoubled = {
            val maps: MutableMap<String, Any?> = mutableMapOf(
                "advertisement_type" to 5,
                "luck_draw_type" to 7,
                "model_type" to 6,
                "reward_id" to it.id
            )
            viewModel.videoType(maps)
        })
    }


    override val layoutResId: Int
        get() = R.layout.activity_main

    override fun viewModel(): MainViewMode {
        return createViewModel()
    }

    override fun stateBar(): StatusBar {
        return StatusBar(isLightMode = false, bottomColor = R.color.FF_1F1E3A)
    }

    override fun initView() {
        //快手-活跃事假
        TurboAgent.onAppActive()
        //快手-日存活事件
        val dayStay = SPStaticUtils.getString(AppConstance.KEY_DAY_STAY)
        val systemTime = System.currentTimeMillis()
        if (dayStay.isNullOrEmpty()) {
            SPStaticUtils.put(
                AppConstance.KEY_DAY_STAY,
                TimeUtils.millis2String(systemTime, "yyyy-MM-dd") + " 00:00:00"
            )
        } else if (systemTime > (TimeUtils.string2Millis(dayStay) + 60 * 60 * 24 * 1000)) {
            TurboAgent.onNextDayStay()
            SPStaticUtils.put(
                AppConstance.KEY_DAY_STAY,
                TimeUtils.millis2String(systemTime, "yyyy-MM-dd") + " 00:00:00"
            )
        }
        TurboAgent.on2dayStay()
        TurboAgent.on3dayStay()
        TurboAgent.on4dayStay()
        TurboAgent.on5dayStay()
        TurboAgent.on6dayStay()
        TurboAgent.onWeekStay()
        TurboAgent.on14dayStay()
        TurboAgent.on30dayStay()
        // 获取唤醒参数
        OpenInstall.getWakeUp(intent, wakeUpAdapter)

        EventBus.getDefault().register(this)

        val mainFragments: MutableList<Fragment> = mutableListOf(
            MainHomeFragment.newInstance(),
            MainHuntFragment.newInstance(),
            MainTaskFragment.newInstance(),
            MainMineFragment.newInstance()
        )
        val mainStatePager = StatePagerAdapter(
            supportFragmentManager,
            FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT,
            mainFragments
        )
        view_pager_main.offscreenPageLimit = mainFragments.size
        view_pager_main.setScrollAnim(false)
        view_pager_main.adapter = mainStatePager

//        nav_view_main.setOnNavigationItemSelectedListener { item ->
//            val position = when (item.itemId) {
//                R.id.item_main_cate -> 1
//                R.id.item_main_cart -> 2
//                R.id.item_main_mine -> 3
//                else -> 0
//            }
//            view_pager_main.currentItem = position
//            return@setOnNavigationItemSelectedListener true
//        }


        with(tab_view_main) {
            addTab(newTab().setCustomView(R.layout.item_tab_home))
            addTab(newTab().setCustomView(R.layout.item_tab_hunt))
            addTab(newTab().setCustomView(R.layout.item_tab_task))
            addTab(newTab().setCustomView(R.layout.item_tab_mine))
        }
        tab_view_main.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) = Unit

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                val position: Int = tab?.position ?: return
                view_pager_main.currentItem = position
                if (position != 3)
                    return
                val view: View = tab_view_main.getTabAt(position)?.customView
                    ?: return
                val tvMineBag: TextView = view.findViewById(R.id.tvMineBag)
                tvMineBag.visibility = View.GONE
            }
        })

        supportFragmentManager.registerFragmentLifecycleCallbacks(
            fragmentLifecycleCallbacks,
            (true)
        )
    }

    override fun initData() {
        viewModel.userInfo()
        if (SPStaticUtils.getBoolean(AppConstance.KEY_NAME_GUIDE)) {
            viewModel.otherGetVersion()
            viewModel.taskSignList(isMain = true)
        } else {
            guidePopup.showPopupWindow()
        }
    }

    override fun initViewMode() {
        viewModel.giveLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.throwable?.msg ?: "未知错误")
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let {
                toast(it.msg ?: "成功")
            }
        })

        viewModel.otherAppLiveData.observe(this, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                if (it.edition_num.compareTo(AppUtils.getAppVersionName()) > 0 && it.enforce_switch == 1) {
                    hintPopup.setType(DialogHintPopup.Type.SHOW_UPDATE).setText(
                        textTitle = "版本更新",
                        textMessage = it.content,
                        textConfirm = "确认",
                        textCancel = "取消"
                    ).showPopupWindow()
                }
            }
        })

        viewModel.userInfoLiveData.observe(this, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                val cartNum: Int? = THApplication.userInfo?.cart_num

                if (cartNum == null) {
                    THApplication.userInfo = it
                } else {
                    val view: View = tab_view_main.getTabAt(3)?.customView
                        ?: return@Observer
                    val tvMineBag: TextView = view.findViewById(R.id.tvMineBag)
                    if (it.cart_num > cartNum) {
                        tvMineBag.visibility = View.VISIBLE
                    } else {
                        tvMineBag.visibility = View.GONE
                    }
                    THApplication.userInfo = it
                }

            }
        })


        viewModel.videoNoRewardLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
            val codeId: String? = response.httpData?.data?.advertising_space
            if (cid == null) {

            } else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdCSJ(mActivity = this, codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdYLH(mActivity = this, codeId = codeId)
            }
        })

        viewModel.videoTypeLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
            val codeId: String? = response.httpData?.data?.advertising_space
            if (cid == null) {

            } else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdCSJ(mActivity = this, codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdYLH(mActivity = this, codeId = codeId)
            }
        })


        viewModel.rewardVerifyAdLiveData.observe(
            this as LifecycleOwner, Observer { isRewardVerifyAd ->
//                if (!isRewardVerifyAd && !viewModel.isRewardVerifyAdSign)
//                    return@Observer
//                val taskSign: TaskSign = viewModel.taskSignLiveData.value?.httpData?.data
//                    ?: return@Observer
//                val signId: Int = taskSign.list[taskSign.sign_num ?: 0].id
//                val videoLogId: String =
//                    viewModel.videoTypeLiveData.value?.httpData?.data?.video_log_id
//                        ?: return@Observer
//                viewModel.taskSign(signId, videoLogId)
//                viewModel.isRewardVerifyAdSign = false

                if (!isRewardVerifyAd)
                    return@Observer
                if (viewModel.isRewardVerifyAdSign) {
                    val taskSign: TaskSign = viewModel.taskSignLiveData.value?.httpData?.data
                        ?: return@Observer
                    val signId: Int = taskSign.list[taskSign.sign_num ?: 0].id
                    val videoLogId: String =
                        viewModel.videoTypeLiveData.value?.httpData?.data?.video_log_id
                            ?: return@Observer
                    viewModel.taskSign(signId, videoLogId)
                    viewModel.isRewardVerifyAdSign = false
                } else {
                    viewModel.videoTypeLiveData.value?.httpData?.data?.let {
                        viewModel.videoEnd(it.video_log_id)
                    }
                }
            })

        viewModel.luckySignLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.throwable?.msg ?: "未知错误")
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                flopPopup.fillData(it).showPopupWindow()
                viewModel.videoNoReward(advertisementType = 3)
            }
        })

        viewModel.videoEndLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let {
                flopPopup.fillData(it.data).showPopupWindow()
                viewModel.videoNoReward(advertisementType = 3)
                if (viewModel.signPopup.isShowing) {
                    viewModel.signPopup.dismiss()
                }
            }
        })

        viewModel.viewAdLiveData.observe(this as LifecycleOwner, Observer { view ->
            view?.let {
                flopPopup.fillViewAd(view)
            }
        })

    }

    override fun onResume() {
        super.onResume()
        TurboAgent.onPageResume()
    }

    override fun onPause() {
        super.onPause()
        TurboAgent.onPagePause()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        supportFragmentManager.unregisterFragmentLifecycleCallbacks(fragmentLifecycleCallbacks)
        wakeUpAdapter = null
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        OpenInstall.getWakeUp(intent, wakeUpAdapter)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(eventBus: MainBean<*, *>) {
        if (eventBus.type !is Action)
            return
        if (eventBus.type == Action.GO_HOME) {
            tab_view_main.getTabAt(0)?.select()
        } else if (eventBus.type == Action.GO_HUNT) {
            tab_view_main.getTabAt(1)?.select()
            //nav_view_main.selectedItemId = nav_view_main.menu.getItem(1).itemId
        } else if (eventBus.type == Action.GO_TASK) {
            tab_view_main.getTabAt(2)?.select()
            //nav_view_main.selectedItemId = nav_view_main.menu.getItem(2).itemId
        } else if (eventBus.type == Action.GO_MINE) {
            viewModel.userInfo()
        }
    }

    private var wakeUpAdapter: AppWakeUpAdapter? = object : AppWakeUpAdapter() {
        override fun onWakeUp(appData: AppData) {
            // 打印数据便于调试
            LogUtils.e("getWakeUp : wakeupData = $appData")
            // 获取渠道数据
            val channelCode = appData.getChannel()
            // 获取绑定数据
            val bindData: String? = appData.getData()
            val schemeData: SchemeData = try {
                GsonUtils.fromJson(bindData, SchemeData::class.java)
            } catch (e: Exception) {
                return
            }
            //赠送给对方
            if (schemeData.type ?: "0" == "2") {
                schemeData.image?.let {
                    cardPopup.setFillImage(it)
                        .setSchemeType(schemeData.type ?: "0")
                        .showPopupWindow()
                    mSchemeData = schemeData
                }
            }
            //领取对方赠送
            if (schemeData.type ?: "0" == "3") {
                schemeData.image?.let {
                    cardPopup.setFillImage(it)
                        .setSchemeType(schemeData.type ?: "0")
                        .showPopupWindow()
                    mSchemeData = schemeData
                }
            }
        }
    }

    /**
     * 下载
     */
    private fun download(url: String?) {
        val intent = Intent()
        intent.action = Intent.ACTION_VIEW
        //if (isApplicationInstall(this, packageName)) {
        //    intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity")
        //}
        intent.data = Uri.parse(url)
        startActivity(intent)
    }

    private fun isApplicationInstall(context: Context, packageName: String): Boolean {
        return try {
            context.packageManager.getPackageInfo(packageName, 0)
            true
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            false
        }
    }
    //getInstall : installData = AppData{channel='', data='{"parent_id":"1"}'}
    //getWakeUp : wakeupData = AppData{channel='', data='{"parent_id":"1"}'}
}